﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Linq.Expressions;
using System.Security.Claims;
using Zhao.Common.EnumEntity;
using Zhao.Common.Helper;
using Zhao.IServer.Log;
using Zhao.IServer.User;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers.Log
{
    /// <summary>
    /// 公告API
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class NotificationsController : ControllerBase
    {
        private readonly INotificationsServer _notificationsServer;
        private readonly IAdminServer _adminServer;
        private readonly IMapper _mapper; 

        public NotificationsController(INotificationsServer notificationsServer, IAdminServer adminServer,IMapper mapper)
        {
            this._notificationsServer = notificationsServer;
            this._adminServer = adminServer;
            this._mapper = mapper;
        }

        /// <summary>
        /// 公告获取数据分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="status"></param>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{status:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{searchaString}")]
        [Route("{pageIndex:int}/{pageSize:int}/{status:int}/{searchaString}")]
        public async Task<JsonResult> GetNotificationsPageInfo(int pageIndex,int pageSize,string searchaString = " ",int status=0)
        {
            Expressionable<Notifications, Venues> expressionable = new Expressionable<Notifications, Venues>();

            string? venunId = User.FindFirst("VenueId")?.Value;

            Guid.TryParse(venunId, out Guid vId);

            expressionable.AndIF(vId != default, (a, b) => a.VenueID == vId);

            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), (a, b) => a.Title.Contains(searchaString) || a.Content.Equals(searchaString));

            expressionable.AndIF(status != 0, (a, b) => a.Status==status);

            var result = await _notificationsServer.QueryNotiPageInfo(expressionable.ToExpression(), pageIndex, pageSize);

            return new JsonResult(result);

        }


        /// <summary>
        /// 添加新公告
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> AddNotification([FromBody]NotificationDTO dto)
        {
            var result = new ApiResult
            {
                Success = false,
                Message = "操作失败"
            };

            int.TryParse(User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value, out int id);

            // 参数基础校验
            if (id == 0)
            {
                return new JsonResult(new ApiResult
                {
                    Success = false,
                    Message = "用户身份凭证无效"
                });
            }

            // 查询管理员权限
            var adminCount = await _adminServer.QueryCountAsync(a => a.Id == id);

            // 权限验证
            if (adminCount==0)
            {
                return new JsonResult(new ApiResult
                {
                    Success = false,
                    Message = "当前用户无管理员权限"
                });
            }

            // 基础参数校验
            if (dto == null)
            {
                result.Message = "参数不能为空";
                return new JsonResult(result);
            }

            if (string.IsNullOrWhiteSpace(dto.Title))
            {
                result.Message = "公告标题不能为空";
                return new JsonResult(result);
            }

            if (string.IsNullOrWhiteSpace(dto.Content))
            {
                result.Message = "公告内容不能为空";
                return new JsonResult(result);
            }

            if (dto.NotificationType != 1 && dto.NotificationType != 5)
            {
                result.Message = "公告类型无效";
                return new JsonResult(result);
            }

            // 获取并验证VenueId
            string? venueIdStr = User.FindFirst("VenueId")?.Value;
            bool isValidVenueId = Guid.TryParse(venueIdStr, out Guid venueId);

            #region 是否添加球馆待定
            //// 球馆管理员必须携带有效VenueId（平台通知VenueId=null）
            //if (dto.NotificationType == 5 && !isValidVenueId)
            //{
            //    result.Message = "VenueId无效或不存在";
            //    return new JsonResult(result);
            //}
            #endregion

            // 转换实体
            var entity = new Notifications
            {
                Title = dto.Title,
                Content = dto.Content,
                PublisherID = id, // 实际项目中需校验用户身份
                VenueID = venueId!=default? venueId:null,
                NotificationType = dto.NotificationType,
                PublishTime = DateTime.Now,
                ExpiryTime = dto.ExpiryTime,
                Image = dto.Image,
                IsDeleted = 0
            };

            // 调用服务层
            var serviceResult = await _notificationsServer.AddAsync(entity);

            result.Success = serviceResult > 0;
            result.Message = serviceResult > 0 ? "操作成功" : "公告添加失败";

            return new JsonResult(result);
        }


        /// <summary>
        /// 修改公告基础信息
        /// </summary>
        [HttpPut("UpdateNotification")]
        public async Task<JsonResult> UpdateNotification([FromBody] NotificationDTO dto)
        {
            var result = new ApiResult { Success = false, Message = "操作失败" };

            // 1. 用户身份验证
            if (!int.TryParse(User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value, out int userId) || userId == 0)
            {
                result.Message = "用户身份凭证无效";
                return new JsonResult(result);
            }

            // 2. 管理员权限验证
            var adminCount = await _adminServer.QueryCountAsync(a => a.Id == userId);
            if (adminCount == 0)
            {
                result.Message = "当前用户无管理员权限";
                return new JsonResult(result);
            }

            // 3. 参数基础校验
            if (dto == null || dto.NotificationID <= 0)
            {
                result.Message = "公告ID无效";
                return new JsonResult(result);
            }
            if (string.IsNullOrWhiteSpace(dto.Title) || string.IsNullOrWhiteSpace(dto.Content))
            {
                result.Message = "标题和内容不能为空";
                return new JsonResult(result);
            }

            // 4. 查询原始公告
            var entity = await _notificationsServer.QueryAsync(dto.NotificationID);
            if (entity == null)
            {
                result.Message = "公告不存在";
                return new JsonResult(result);
            }

            // 6. 更新字段（避免覆盖不需要修改的字段）
            entity.Title = dto.Title;
            entity.Content = dto.Content;
            entity.ExpiryTime = dto.ExpiryTime;
            entity.Image = dto.Image ?? entity.Image; // 保留原图如果未传新图
            entity.Status = dto.Status;

            // 7. 调用服务层更新
            var updateResult = await _notificationsServer.UpdateAsync(entity);

            result.Success = updateResult;
            result.Message = updateResult ? "公告修改成功" : "公告修改失败";

            return new JsonResult(result);
        }


        /// <summary>
        /// 修改公告状态（1=展示中,3=已过期,5=已下架）
        /// </summary>
        [HttpPatch("UpdateStatus")]
        public async Task<JsonResult> UpdateNotificationStatus(int notificationId, short status)
        {
            var result = new ApiResult { Success = false, Message = "操作失败" };

            // 1. 用户身份验证
            if (!int.TryParse(User.FindFirst("UserId")?.Value, out int userId) || userId == 0)
            {
                result.Message = "用户身份凭证无效";
                return new JsonResult(result);
            }

            // 2. 管理员权限验证
            var adminCount = await _adminServer.QueryCountAsync(a => a.Id == userId);
            if (adminCount == 0)
            {
                result.Message = "当前用户无管理员权限";
                return new JsonResult(result);
            }

            // 3. 状态有效性验证
            if (status != 1 && status != 3 && status != 5)
            {
                result.Message = "无效状态值（允许值:1,3,5）";
                return new JsonResult(result);
            }

            // 4. 查询公告
            var entity = await _notificationsServer.QueryAsync(notificationId);
            if (entity == null)
            {
                result.Message = "公告不存在";
                return new JsonResult(result);
            }

            //后台公告或者球馆发布的用户公告只能有一条是展示中的，需要进行排查

            //后台
            if (entity.NotificationType == 1 && status==1)
            {
                var troubleshootInfo = await _notificationsServer.QueryListAsync(x => x.Status == 1 && x.NotificationType == entity.NotificationType && x.NotificationID != entity.NotificationID );

                if (troubleshootInfo != null)
                {
                    result.Message = "只允许有一条在发布的公告";
                    return new JsonResult(result);
                }
            }
            //球馆用户公告后期在开发

            // 6. 更新状态与软删除标记
            entity.Status = status;

            // 7. 调用服务层更新
            var updateResult = await _notificationsServer.UpdateAsync(entity);

            result.Success = updateResult;
            result.Message = updateResult ? "状态更新成功" : "状态更新失败";

            return new JsonResult(result);
        }



        /// <summary>
        /// 获取当前状态为展示的公告
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetNotice(int nType=1)
        {
            var result = new ApiResult<NotificationDTO>();

            var data = await _notificationsServer.QueryAsync(x=>x.Status==1 && x.NotificationType==nType);

            if (data == null)
            {
                result.Message = "未查询到数据";
                result.Success= false;
                return new JsonResult(result);
            }

            result.Data = _mapper.Map<NotificationDTO>(data);
            result.Message = "查询成功";
            result.Success = true;

            return new JsonResult(result);
        }

        /// <summary>
        /// 获取最新的公告
        /// </summary>
        /// <param name="notificationType">公告类型：1-后台通知，5-用户通知，默认为1</param>
        /// <returns>最新的公告信息</returns>
        [HttpGet("latest")]
        [AllowAnonymous] // 允许匿名访问，便于前端获取
        public async Task<JsonResult> GetLatestNotification(short notificationType = 1)
        {
            var result = new ApiResult<NotificationDTO>();

            try
            {

                // 调用服务层方法获取最新公告
                var latestNotification = await _notificationsServer.GetLatestNotification(notificationType);

                if (latestNotification == null)
                {
                    result.Success = false;
                    result.Message = "未找到最新公告";
                    return new JsonResult(result);
                }

                result.Success = true;
                result.Message = "获取最新公告成功";
                result.Data = latestNotification;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = $"获取最新公告失败: {ex.Message}";
            }

            return new JsonResult(result);
        }
    }
}
